<template>
  <div class="new-project-container">
    <div class="header">
      <h2>新建项目</h2>
      <p>创建一个新的软件度量项目</p>
    </div>
    <div class="content">
      <el-form :model="projectForm" label-width="120px">
        <el-form-item label="项目名称">
          <el-input v-model="projectForm.name" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="上传源代码">
          <el-upload
            ref="sourceCodeUpload"
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleSourceCodeChange"
            :before-upload="beforeSourceCodeUpload"
            :limit="1"
            :on-exceed="handleSourceCodeExceed"
            :on-remove="() => projectForm.sourceCode = null"
            accept=".zip">
            <i class="fas fa-upload"></i>
            <div class="el-upload__text">将源代码压缩包拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">仅支持 .zip 格式的源代码压缩包，且只能上传一个文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="上传设计图">
          <el-upload
            ref="designUpload"
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleDesignChange"
            :before-upload="beforeDesignUpload"
            :limit="1"
            :on-exceed="handleDesignExceed"
            :on-remove="() => projectForm.designFile = null"
            accept=".oom">
            <i class="fas fa-upload"></i>
            <div class="el-upload__text">将设计图文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">仅支持 .oom 格式的设计图文件，且只能上传一个文件</div>
          </el-upload>
        </el-form-item>
      </el-form>

      <!-- 项目分析结果表格 -->
      <div v-if="projectSummary" class="analysis-result">
        <h3>项目分析结果</h3>
        <div class="table-container">
          <el-table :data="[projectSummary]" border style="width: 100%">
            <el-table-column prop="totalFiles" label="总文件数"></el-table-column>
            <el-table-column prop="totalLines" label="总代码行数"></el-table-column>
            <el-table-column prop="totalComments" label="总注释行数"></el-table-column>
            <el-table-column prop="commentDensity" label="注释密度"></el-table-column>
          </el-table>
          <el-table :data="[projectSummary]" border style="width: 100%; margin-top: 10px;">
            <el-table-column prop="totalComplexity" label="总圈复杂度"></el-table-column>
            <el-table-column prop="goodFiles" label="良好文件数"></el-table-column>
            <el-table-column prop="poorFiles" label="较差文件数"></el-table-column>
            <el-table-column prop="averageFiles" label="平均文件数"></el-table-column>
          </el-table>
        </div>

        <!-- 功能点度量雷达图 -->
        <div class="radar-chart-container">
          <div ref="radarChart" style="width: 100%; height: 400px;"></div>
        </div>

        
      </div>
      <!-- 按钮组 -->
      <div class="button-group">
          <el-button type="primary" @click="createProject" :loading="$store.getters.getLoading">创建项目</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import * as echarts from 'echarts'

export default {
  name: 'NewProjectView',
  data() {
    return {
      projectForm: {
        name: '',
        sourceCode: null,
        designFile: null
      },
      radarChart: null
    }
  },
  computed: {
    projectSummary() {
      return this.$store.getters.getSourceCodeData?.projectSummary;
    }
  },
  methods: {
    beforeSourceCodeUpload(file) {
      const isZip = file.type === 'application/zip' || file.name.endsWith('.zip');
      if (!isZip) {
        this.$message.error('只能上传 .zip 格式的源代码压缩包！');
        return false;
      }
      return true;
    },
    beforeDesignUpload(file) {
      const isOom = file.name.endsWith('.oom');
      if (!isOom) {
        this.$message.error('只能上传 .oom 格式的设计图文件！');
        return false;
      }
      return true;
    },
    handleSourceCodeExceed() {
      this.$message.warning('只能上传一个源代码文件！');
    },
    handleDesignExceed() {
      this.$message.warning('只能上传一个设计图文件！');
    },
    handleSourceCodeChange(file) {
      console.log('源代码文件已上传:', file)
      this.projectForm.sourceCode = file
    },
    handleDesignChange(file) {
      console.log('设计图文件已上传:', file)
      this.projectForm.designFile = file
    },
    createProject() {
      if (!this.projectForm.sourceCode && !this.projectForm.designFile) {
        this.$message.warning('请至少上传一种文件！');
        return;
      }

      if (!this.projectForm.sourceCode || !this.projectForm.designFile) {
        this.$confirm('只上传一种文件会导致部分度量功能无法使用，是否确定继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submitProject();
        }).catch(() => {
          this.$message.info('已取消创建项目');
        });
      } else {
        this.submitProject();
      }
    },
    async submitProject() {
      this.$store.dispatch('setLoading', true);
      try {

        // 上传源代码文件
        if (this.projectForm.sourceCode) {
          const sourceCodeFormData = new FormData();
          sourceCodeFormData.append('file', this.projectForm.sourceCode.raw);

          const sourceCodeResponse = await axios.post('http://localhost:8080/api/metrics/analyze', sourceCodeFormData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });
          this.$store.dispatch('setSourceCodeData', sourceCodeResponse.data);
          console.log("源代码数据:", sourceCodeResponse.data);
        }

        // 上传设计图文件
        if (this.projectForm.designFile) {
          const designFormData = new FormData();
          designFormData.append('file', this.projectForm.designFile.raw);

          const designResponse = await axios.post('http://localhost:8080/api/oom-analysis/upload', designFormData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });
          this.$store.dispatch('setDesignData', designResponse.data);
          console.log('设计图数据:', designResponse.data);
        }

        this.$message.success('项目创建成功！');
      } catch (error) {
        console.error('创建项目失败:', error);
        this.$message.error(error.message || '项目创建失败，请稍后重试');
      } finally {
        this.$store.dispatch('setLoading', false);
      }
    },
    resetForm() {
      this.projectForm = {
        name: '',
        sourceCode: null,
        designFile: null
      }
      // 清除全局变量中的数据
      this.$store.dispatch('setSourceCodeData', null);
      this.$store.dispatch('setDesignData', null);
      // 清除上传的文件
      if (this.$refs.sourceCodeUpload) {
        this.$refs.sourceCodeUpload.clearFiles();
      }
      if (this.$refs.designUpload) {
        this.$refs.designUpload.clearFiles();
      }
    },
    initRadarChart() {
      if (!this.projectSummary) return;
      
      // 如果已经存在图表实例，先销毁
      if (this.radarChart) {
        this.radarChart.dispose();
        this.radarChart = null;
      }
      
      // 确保DOM元素存在
      if (!this.$refs.radarChart) return;
      
      // 创建新的图表实例
      this.radarChart = echarts.init(this.$refs.radarChart);
      
      const option = {
        title: {
          text: '项目功能点度量分析',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          data: ['功能点度量值'],
          bottom: 0
        },
        radar: {
          indicator: [
            { name: '外部输入', max: Math.max(this.projectSummary.externalInputs || 0, 10) },
            { name: '外部输出', max: Math.max(this.projectSummary.externalOutputs || 0, 10) },
            { name: '外部查询', max: Math.max(this.projectSummary.externalQueries || 0, 10) },
            { name: '内部逻辑文件', max: Math.max(this.projectSummary.internalLogicalFiles || 0, 10) },
            { name: '外部接口文件', max: Math.max(this.projectSummary.externalInterfaces || 0, 10) }
          ],
          radius: '65%'
        },
        series: [{
          type: 'radar',
          data: [{
            value: [
              this.projectSummary.externalInputs || 0,
              this.projectSummary.externalOutputs || 0,
              this.projectSummary.externalQueries || 0,
              this.projectSummary.internalLogicalFiles || 0,
              this.projectSummary.externalInterfaces || 0
            ],
            name: '功能点度量值',
            areaStyle: {
              color: 'rgba(64, 158, 255, 0.3)'
            },
            lineStyle: {
              color: '#409EFF'
            }
          }]
        }]
      };
      
      this.radarChart.setOption(option);
      
      // 添加窗口大小改变时的自适应
      window.addEventListener('resize', this.handleResize);
    },
    handleResize() {
      if (this.radarChart) {
        this.radarChart.resize();
      }
    }
  },
  mounted() {
    // 组件挂载时初始化雷达图
    this.$nextTick(() => {
      this.initRadarChart();
    });
  },
  updated() {
    // 组件更新时重新初始化雷达图
    this.$nextTick(() => {
      this.initRadarChart();
    });
  },
  beforeDestroy() {
    // 移除窗口大小改变的监听
    window.removeEventListener('resize', this.handleResize);
    if (this.radarChart) {
      this.radarChart.dispose();
      this.radarChart = null;
    }
  }
}
</script>

<style scoped>
.new-project-container {
  padding: 20px;
  height: 100%;
  background-color: #ffffff;
}

.header {
  margin-bottom: 30px;
  text-align: center;
}

.header h2 {
  color: #333333;
  margin-bottom: 10px;
  font-size: 24px;
}

.header p {
  color: #606266;
  font-size: 14px;
}

.content {
  max-width: 800px;
  margin: 0 auto;
}

.upload-demo {
  width: 100%;
  margin-bottom: 20px;
}

.analysis-result {
  margin-top: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.analysis-result h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
}

.table-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 100%;
}

:deep(.el-table) {
  margin-bottom: 0;
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body-wrapper) {
  width: 100% !important;
}

:deep(.el-table__header-wrapper) {
  width: 100% !important;
}

.radar-chart-container {
  margin-top: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.radar-chart-container h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
  text-align: center;
}

.button-group {
  margin-top: 20px;
  text-align: right;
  padding-right: 20px;
}
</style> 